/*   Copyright 2012 Julian Aloofi

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

#include "GameManager.hpp"

Tacticus::GameManager *Tacticus::GameManager::instance = 0;

Tacticus::GameManager &Tacticus::GameManager::getInstance()
{
    if (!instance)
        instance = new GameManager();
    return *instance;
}

void Tacticus::GameManager::destroy()
{
    if (instance)
        delete instance;
    instance = 0;
}

const Tacticus::Board &Tacticus::GameManager::getGameBoard() const
{
    return gameBoard;
}

const Tacticus::Common::CoordinateField
    &Tacticus::GameManager::getLastOrigin() const
{
    return lastOrigin;
}

const Tacticus::Common::CoordinateField
    &Tacticus::GameManager::getLastTarget() const
{
    return lastTarget;
}

void Tacticus::GameManager::newGame()
{
    gameBoard = Board();
    lastOrigin = Common::CoordinateField();
    lastTarget = Common::CoordinateField();
}

void Tacticus::GameManager::placePiece(const Tacticus::Field &field,
    const Tacticus::Common::Coordinate &coordinate)
{
    gameBoard.place(field, coordinate);
}

void Tacticus::GameManager::makeTurn(const Tacticus::Common::Coordinate &origin,
    const Tacticus::Common::Coordinate &target)
{
    const std::pair<Common::CoordinateField, Common::CoordinateField> result
        = gameBoard.makeTurn(origin, target);
    lastOrigin = result.first;
    lastTarget = result.second;
}

void Tacticus::GameManager::handleEvent(boost::shared_ptr<Tacticus::Event>
    event)
{
    switch (event->getType())
    {
    case Events::PLACEMENT_EVENT:
    {
        bool successful = true;
        boost::shared_ptr<PlacementEvent> placementEvent =
            boost::static_pointer_cast<PlacementEvent>(event);
        try
        {
            placePiece(placementEvent->getToPlace(),
                placementEvent->getWhereToPlace());
        }
        catch (Common::InvalidPlacementException &e)
        {
            // TODO error handling (possibly drawing to screen)
            successful = false;
        }
        if (successful)
        {
            EventManager::getInstance().queueEvent(boost::shared_ptr<
                SuccessfulPlacementEvent>(new SuccessfulPlacementEvent(
                placementEvent)));
        }
        break;
    }
    case Events::MAKETURN_EVENT:
    {
        bool successful = true;
        boost::shared_ptr<MakeTurnEvent> makeTurnEvent =
            boost::static_pointer_cast<MakeTurnEvent>(event);
        try
        {
            makeTurn(makeTurnEvent->getWhereFrom(),
                makeTurnEvent->getWhereTo());
        }
        catch (Common::InvalidTurnException &e)
        {
            // TODO proper error handling
            successful = false;
        }
        if (successful)
        {
            EventManager::getInstance().queueEvent(boost::shared_ptr<
                SuccessfulTurnEvent>(new SuccessfulTurnEvent(lastOrigin,
                lastTarget)));
            if (gameBoard.isGameOver())
            {
                EventManager::getInstance().queueEvent(boost::shared_ptr<
                    GameOverEvent>(new GameOverEvent(
                    gameBoard.getCurrentPlayer())));
            }
        }
        break;
    }
    case Events::NEWGAME_EVENT:
    {
        newGame();
        break;
    }
    case Events::PLACEMENTDONE_EVENT:
    {
        boost::shared_ptr<PlacementDoneEvent> placementDoneEvent = boost::
            static_pointer_cast<PlacementDoneEvent>(event);
        if (gameBoard.areAllPlaced(placementDoneEvent->getDonePlayer()) &&
            gameBoard.validTurnsAvailableFor(placementDoneEvent->getDonePlayer()
            ))
        {
            EventManager::getInstance().queueEvent(boost::shared_ptr<
                SuccessfulPlacementDoneEvent>(new SuccessfulPlacementDoneEvent(
                placementDoneEvent)));
        }
        break;
    }
    case Events::SUCCESSFULPLACEMENTDONE_EVENT:
    {
        if (gameBoard.areAllPlaced())
        {
            gameBoard.startGame();
        }
        break;
    }
    default:
    {
        throw Common::EventHandlingException(
            "Unhandled event passed to GameManager");
    }
    }
}
